#!/usr/bin/python
# coding=utf-8
import hashlib
import json
import base64
import os
import logging
import web
import requests
from web.contrib.template import render_jinja
from ccc.dba import db_factory
from ccc.settings import WEIXIN_TOKEN, BAIDU_AK
from ccc.lrweixin import parse_xml_message, TextReply, Reply, TextMessage, LocationMessage
from ccc.services import handle_request

LOG = logging.getLogger(__name__)

urls = (
    '/', 'Index',
    '/wx', 'Wx'
)
app = web.application(urls, globals())
renderer = render_jinja('static', encoding='utf-8')


class Index(object):
    def GET(self):
        return json.dumps({
            'id': 1,
            'sensorId': 2
        })


class Wx(object):
    def GET(self):
        data = web.input()
        if len(data) == 0:
            return 'hello, this is WeChat Handle view'

        signature = data.signature
        timestamp = data.timestamp
        nonce = data.nonce
        echostr = data.echostr
        token = WEIXIN_TOKEN

        to_hash = [token, timestamp, nonce]
        to_hash.sort()
        sha1 = hashlib.sha1()
        map(sha1.update, to_hash)

        hashcode = sha1.hexdigest()
        if hashcode == signature:
            return echostr
        else:
            return ''

    def POST(self):
        data = web.data()
        message = parse_xml_message(data)
        if isinstance(message, TextMessage):
            LOG.info(u'接收到来自[%s]的消息：%s', message.source_user, message.content)
            content = handle_request(message, *filter(bool, message.content.split(' ')))
            LOG.debug(u'响应为：%s', content)
            return TextReply(message.source_user, message.target_user, content).dumps()
        elif isinstance(message, LocationMessage):
            LOG.info(u'接收到来自[%s]的位置信息[%d, %d]', message.source_user, message.x, message.y)
            location_result = requests.get(u'http://api.map.baidu.com/geocoder/v2/', params={
                'location': '{},{}'.format(message.x, message.y),
                'output': 'json',
                'ak': BAIDU_AK
            }).json()
            location_components = location_result['result']['addressComponent']
            location = u'{}{}{}'.format(
                location_components['province'],
                location_components['city'] if location_components['province'] != location_components['city'] else u'',
                location_components['district']
            )

            LOG.info(u'用户{}的位置解析为{}', message.source_user, location)
            content = handle_request(message, u'报位置', location, message.y, message.x)
            LOG.debug(u'响应为：%s', content)
            return TextReply(message.source_user, message.target_user, content).dumps()
        else:
            return Reply().dumps()


application = app.wsgifunc()


def main():
    LOG.info('to start')
    app.run()


if __name__ == '__main__':
    main()
